package configs

import (
	"errors"
	"fmt"
	"path/filepath"
	"time"

	beego "github.com/beego/beego/v2/server/web"
	"github.com/spf13/viper"
)

var (
	Manager      = getManager()
	managerError error
)

func ConfigInit() error {
	if ProductName == "" {
		return errors.New("环境变量[BEEGO_PRODUCT]为空")
	}

	if EnvName == "" {
		return errors.New("环境变量[BEEGO_ENV]为空")
	}

	if RunMode == "" {
		return errors.New("环境变量[BEEGO_RUNMODE]为空")
	}

	if ExecPath == "" {
		return errors.New("os.Executable()获取当前程序目录失败")
	}

	if fmt.Sprintf("%s_%s", ProductName, EnvName) != RunMode {
		return errors.New("环境变量[BEEGO_RUNMODE]与[BEEGO_PRODUCT]_[BEEGO_ENV]不匹配")
	}

	if managerError != nil {
		return errors.New("configs.Manager初始化失败")
	}

	// 手动加载beego配置
	err := beego.LoadAppConfig("ini", fmt.Sprintf("%s/conf/%s.beego.conf", ExecPath, ProductName))
	if err != nil {
		return errors.New(fmt.Sprintf("加载beego配置失败:%s", err.Error()))
	}

	return nil
}

func getManager() *viper.Viper {

	manager := viper.New()

	path := filepath.Join(ExecPath, "conf")
	fileName := getConfigFileName()

	manager.SetConfigType("yaml")
	manager.AddConfigPath(path)
	manager.SetConfigName(fileName)

	managerError = manager.ReadInConfig()
	if managerError != nil {
		fmt.Println(time.Now().Format("2006-01-02 15:04:05"), " 配置文件读取失败:path=", path, ",fileName=", fileName, ",err=", managerError.Error())
	}

	return manager
}

func getConfigFileName() string {

	fileName := fmt.Sprintf("%s.app.yaml", RunMode)

	return fileName
}
